package pack0714.cn;

public class MyRun1 implements Runnable {

    private Person p1 ;

    private Person p2 ;

    int n = 0 ;

    public MyRun1(Person p1,Person p2){
        this.p1 = p1 ;
        this.p2 = p2 ;
    }


    @Override
    public void run() {
        String name = Thread.currentThread().getName() ;
        if("t".equals(name)){
            synchronized (p1){   //给p1对象上一把锁
                System.out.println(Thread.currentThread().getName() + "进入了同步块,锁定了p1资源");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (p2){
                    System.out.println(Thread.currentThread().getName() + "醒来了,准备锁定p2资源");
                }
            }
        }else{
            synchronized (p2){   //给p1对象上一把锁
                System.out.println(Thread.currentThread().getName() + "进入了同步块,锁定了p2资源");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (p1){
                    System.out.println(Thread.currentThread().getName() + "醒来了,准备锁定p1资源");
                }
            }
        }
    }
}
